﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JXT.PrimaryKey.Batman.Core.Infrastructure
{
    /// <summary>
    /// 线程级别独享容器，此对象在同一线程共享容器，其方法是线程安全的
    /// <remarks>
    /// 此容器供Unity使用，可以实现线程间对象的隔离和单次请求及时回收数据
    /// </remarks>
    /// </summary>
    public class ThreadObjectContainer : IDisposable
    {
        [ThreadStatic]
        private static IDictionary<string, object> _items;

        /// <summary>
        /// 默认构造方法
        /// </summary>
        public ThreadObjectContainer()
        {
        }

        /// <summary>
        /// 数据容器
        /// </summary>
        public IDictionary<string, object> Items
        {
            get {
                if (_items == null)
                {
                    _items = new Dictionary<string, object>();
                }
                return _items; 
            }
        }

        /// <summary>
        /// 清理数据方法
        /// </summary>
        public void Dispose()
        {
            string[] keys = Items.Keys.ToArray();
            foreach (var key in keys)
            {
                if (Items.ContainsKey(key) && Items[key] is IDisposable)
                {
                    (Items[key] as IDisposable).Dispose();
                }
            }
            Items.Clear();
        }
    }
}
